<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表v-loading="listLoading"-->
    <el-table :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange" highlight-current-row
      style="width: 100%">
      <!--多选框-->
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" width="70" label="序号"> </el-table-column>
      <el-table-column prop="articleName" label="文章名称" width="120">
      </el-table-column>
      <el-table-column prop="articleTag" label="文章标签" width="120">
      </el-table-column>
      <el-table-column prop="articlePic" label="文章封面" width="120">
        <template scope="scope">
          <img :src="scope.row.articlePic" height="50px" />
        </template>
      </el-table-column>
      <el-table-column prop="at.typeName" label="文章类型" width="120">
      </el-table-column>
      <el-table-column prop="articleState" label="文章状态" width="120">
        <template scope="scope">
          <span v-if="scope.row.articleState == 0" style="color: coral">草稿</span>
          <span v-else-if="scope.row.articleState == 1" style="color: green">发布</span>
          <span v-else style="color: gray">弃用</span>
        </template>
      </el-table-column>
      <el-table-column prop="topState" label="是否置顶" width="120">
        <template scope="scope">
          <span v-if="scope.row.topState == 0" style="color: gray">不置顶</span>
          <span v-else style="color: gold">置顶</span>
        </template>
      </el-table-column>
      <el-table-column prop="user.realName" label="发布人" width="120">
      </el-table-column>
      <el-table-column prop="articleReadCount" label="阅读量" width="120">
      </el-table-column>
      <el-table-column prop="articleStarNum" label="点赞数" width="120">
      </el-table-column>
      <el-table-column prop="articleCommentNum" label="评论数" width="120">
      </el-table-column>
      <el-table-column prop="createTime" label="发布时间" width="200">
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="200">
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totals"
        style="float: right">
      </el-pagination>
    </el-col>

    <!--添加或修改界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="文章名字" prop="articleName">
          <el-input v-model="saveForm.articleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章封面" prop="articlePic">
          <el-upload class="upload-demo" action="http://localhost:8080/minio" name="file" :on-remove="handleRemove"
            :on-success="handleSuccess" :on-exceed="exceed" :file-list="fileList" :limit="1"
            accept=".jpg,.jpeg,.png,.gif" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传指定类型的图片</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章标签" prop="articleTag">
          <el-input v-model="saveForm.articleTag" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章类型" prop="articleType">
          <el-cascader v-model="saveForm.articleType" :options="options" :props="{
            checkStrictly: true,
            value: 'id',
            label: 'typeName',
            emitPath: false,
          }" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="文章状态">
          <template>
            <el-radio v-model="saveForm.articleState" :label="0">草稿</el-radio>
            <el-radio v-model="saveForm.articleState" :label="1">发布</el-radio>
            <el-radio v-model="saveForm.articleState" :label="2">弃用</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="是否置顶">
          <template>
            <el-radio v-model="saveForm.topState" :label="1">置顶</el-radio>
            <el-radio v-model="saveForm.topState" :label="0">不置顶</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="文章简介" prop="articleRemark">
          <el-input v-model="saveForm.articleRemark" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" prop="articleContent">
          <div class="edit_container">
            <quill-editor v-model="saveForm.articleContent" :options="quillOption" @ready="onEditorReady($event)">
            </quill-editor>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import quillConfig from "../../common/js/quill-config";
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
  [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{ indent: "-1" }, { indent: "+1" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{ direction: "rtl" }], // 文本方向-----[{'direction': 'rtl'}]
  [{ size: ["small", false, "large", "huge"] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{ font: [] }], // 字体种类-----[{ font: [] }]
  [{ align: [] }], // 对齐方式-----[{ align: [] }]
  ["clean"], // 清除文本格式-----['clean']
  ["image", "link"], // 链接、图片、视频-----['link', 'image', 'video']
];
export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      quillOption:quillConfig,
      fileList: [
        {
          name: "",
          url: "",
        }
      ], //上传的文件列表
      imgPrefix: "http://localhost:9000/testbucket/",
      editorOption: {
        modules: {
          //工具栏定义的
          toolbar: toolbarOptions,
        },
        //主题
        theme: "snow",
        placeholder: "请开始书写您的博客内容...",
      },
      options: [], //类型树集合
      //1.分页查询相关数据
      totals: 0, //总记录条数
      currentPage: 1, //当前页,要传递到后台的
      pageSize: 5, //每页显示多少条
      tableDatas: [], //当前页数据
      listLoading: false,

      //2.高级查询相关数据
      keyword: "",

      //3.删除相关数据

      //4.批量删除相关数据
      sels: [], //存储多选记录

      //5.添加和修改相关数据
      saveFormVisible: false,
      title: "",
      saveForm: {
        id: null,
        articlePic: null,
        articleName: null,
        articleTag: null,
        articleType: null,
        articleState: null,
        topState: null,
        publishId: null,
        createTime: null,
        updateTime: null,
        articleReadCount: null,
        articleStarNum: null,
        articleCommentNum: null,
        articleRemark: null,
        articleContent: null,
      },

      //6.添加和修改校验规则-表单项校验
      saveFormRules: {
        articleName: [
          { required: true, message: "请输入文章名称", trigger: "blur" },
        ],
        articleRemark: [
          { required: true, message: "请输入文章简介", trigger: "blur" },
        ],
        articleContent: [
          { required: true, message: "请输入文章内容", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleSuccess(response, file, fileList) {
      let filepath = this.imgPrefix + response.data;

      //维护fileList,成功修改,先清空上一次的,再添加!!!
      this.fileList = [];
      this.fileList.push({ url: filepath });

      this.saveForm.articlePic = filepath;
    },
    //删除文件的钩子方法
    handleRemove(file, fileList) {
      let filename = null;
      if (file.response) {
        filename = file.response.data;
      } else {
        filename = file.url.substring(file.url.lastIndexOf("/") + 1);

      }
      //删除mioIO上的图片
      this.$http.delete("/minio/" + filename).then((res) => {
        if (res.data.success) {
          this.$message.success("删除成功");
        } else {
          this.$message.error("网络异常，请稍后重试！【400/404/...】");
        }
      }).catch(() => {
        this.$message.error("")
      });
    },
    //超出文件个数的钩子方法
    exceed() {
      this.$message.error("最多只能上传一个文件");
    },
    onEditorReady(editor) {
      //当富文本编辑框初始化好执行
      console.log("富文本编辑框初始化---------完成");
    },
    //1.分页查询相关方法
    //1.1.获取列表数据
    getTableData() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword,
      };
      this.listLoading = true; //显示加载圈!!!
      //分页查询
      this.$http.post("/article", para).then((result) => {
        console.log(result);
        this.totals = result.data.total; //注意后端返回的是total,而不是totals!!!,可以打印result查看
        this.tableDatas = result.data.list;
        this.listLoading = false; //关闭加载圈!!!
      });
    },
    //1.2.选择第几页时触发
    handleCurrentChange(curentPage) {
      this.currentPage = curentPage;
      this.getTableData(); //获取列表数据
    },
    //1.3.选择每页显示记录条数时触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getTableData(); //获取列表数据
    },

    //2.高级查询相关方法
    keywordQuery() {
      this.currentPage = 1; //!!!

      this.getTableData(); //调用调用分页列表方法,因为关键字keyword已经进行了v-model的双向绑定!
    },

    //3.删除相关方法
    handleDel(row) {
      this.$confirm("此操作将永久删除该文章类型，是否继续？", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 获取当前用户的id
          this.$http
            .delete("/article/" + row.id)
            .then((res) => {
              console.log(res);
              if (res.data.success) {
                // 删除成功
                this.$message.success(res.data.msg);

                let lastPage = Math.ceil(this.totals / this.pageSize); // 向上取整，计算出当前的总页数，这个页数就是最后一页

                // 删除最后一页，只有一条数据，要返回上一页，并且最后一页不能是第一页
                if (
                  this.currentPage != 1 &&
                  this.totals % this.pageSize == 1 &&
                  this.currentPage == lastPage
                ) {
                  // 设置返回上一页
                  this.currentPage = this.currentPage - 1;
                }
                // 删除成功，重新查询列表
                this.getTableData();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(() => {
              this.$message.error("网络异常，请稍后重试！【400/404/...】");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    //4.批量删除相关方法
    //4.1.选项改变时触发
    handleSelectionChange(val) {
      console.log(val);
      //传入的参数是选中的行的数据,行的数组,我们要从这个数组获取id,得到一个id数组[1,2,3,4]
      this.sels = val.map((u) => u.id); //!!!数组的map映射!!!
      console.log(this.sels);
    },
    //4.2.批量删除
    handlePatchDel() {
      this.$confirm("此操作将永久删除选中的文章类型，是否继续？", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //获取当前用户的id
          this.$http
            .patch("/article", this.sels)
            .then((res) => {
              if (res.data.success) {
                //删除成功
                this.$message.success(res.data.msg);

                //批量删除,直接返回首页第一页
                this.currentPage = 1;

                //删除成功，重新查询列表
                this.getTableData();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(() => {
              this.$message.error("网络异常，请稍后重试！【400/404/...】");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    //5.添加和修改相关方法
    //5.1.点击添加弹出对话框
    handleAdd() {
      this.fileList = [];//添加清空!!!
      //1.清空form表单
      this.saveForm = { articleState: 0, topState: 0 };
      //2.设置标题
      this.title = "新增";
      //3.弹出模态框
      this.saveFormVisible = true;
      this.getTypeTree(-1);
    },
    //5.2.点击修改弹出对话框
    handleEdit(row) {
      //1.设置标题
      this.title = "编辑";

      //2.将row对象拷贝给一个空对象,空对象赋值给saveForm.避免修改的时候影响行数据
      this.saveForm = Object.assign({}, row); //深拷贝!!!
      this.fileList = [];
      if (this.saveForm.articlePic) {
        //
        this.fileList.push({ url: row.articlePic });
      }

      //3.弹出模态框
      this.saveFormVisible = true;
      this.getTypeTree(-1);
    },
    //得到类型树
    getTypeTree(id) {
      this.$http
        .get("/article/getTypeTree/" + id)
        .then((res) => {
          this.options = res.data.data;
        })
        .catch((res) => {
          this.$message.error("网络异常，请稍后重试！【400/404/...");
        });
    },
    //5.3.提交表单数据操作数据库
    saveSubmit() {
      //form的属性 ref="saveForm"
      this.$refs["saveForm"].validate((valid) => {
        //判断校验是否通过
        if (valid) {
          //1.点击提交,saveForm已经有值,双向绑定的,直接发送保存的异步请求
          this.$http
            .put("/article", this.saveForm)
            .then((res) => {
              //console.log(res);
              if (res.data.success) {
                //保存成功
                //1.提示操作成功
                this.$message.success(res.data.msg);
                //2.关闭对话框
                this.saveFormVisible = false;

                //3.1如果是新增,则跳转到最后一页
                if (this.saveForm.id == null) {
                  //新增
                  //3.2 新增多了一条,所以改变总条数,触发重新计算总页数!!!
                  this.totals = this.totals + 1;

                  //3.3赋值最后一页
                  this.currentPage = Math.ceil(this.totals / this.pageSize); //页码重新赋值
                }

                //修改停留在当前页,默认就是当前页,所以不用操作,重新查询列表数据即可↓
                //重新查询数据
                this.getTableData();
              } else {
                //保存失败
                this.$message.error(res.data.msg);
              }
            })
            .catch(() => {
              this.$message.error("网络异常，请稍后重试！【400/404/...】");
            });
        } else {
          this.$message.error("校验不通过,必填项没有内容");
          return false;
        }
      });
    },
  },
  mounted() {
    this.getTableData();
  },
};
</script>

<style scoped></style>
